package com.siyi.fpvdemo;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.FrameLayout;

import com.siyi.imagetransmission.config.SettingsConfig;
import com.siyi.imagetransmission.connection.ConnectionListener;
import com.siyi.imagetransmission.connection.ConnectionManager;
import com.siyi.imagetransmission.contract.protocol.IRCProtocolListener;
import com.siyi.imagetransmission.contract.protocol.Param24G;
import com.siyi.imagetransmission.contract.protocol.Param58G;
import com.siyi.imagetransmission.contract.protocol.e;
import com.siyi.imagetransmission.contract.protocol.rtsp.RtspConstants;
import com.siyi.imagetransmission.decoder.DecodeConfig;
import com.siyi.imagetransmission.decoder.IDecodeListener;
import com.siyi.imagetransmission.log.Logcat;

import java.lang.ref.WeakReference;

public class VideoActivity extends AppCompatActivity implements ConnectionListener {
    private static final String TAG = "VideoActivity";
    private ViewGroup mContainer;
    private SurfaceView mSurfaceView;
    private SurfaceView mPreView = null;

    private ConnectionManager mConnectionManager;
    private VideoActivity.MainHandler mMainHandler;

    private int mPreViewWidth  = 600;
    private int mPreViewHeight = 450;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHideVirtualKey(getWindow());

        setContentView(R.layout.activity_video);
        mPreViewWidth  = getResources().getDimensionPixelSize(R.dimen.second_surface_width);
        mPreViewHeight = getResources().getDimensionPixelSize(R.dimen.second_surface_height);
        Log.e("Size", "Width:" + mPreViewWidth + " Height:" + mPreViewHeight);

        mMainHandler = new MainHandler(new WeakReference<>(this));
        initView();
        // 配置初始化，这个是可选的。
        initConfig();
        mConnectionManager = ConnectionManager.getInstance(this);
        mConnectionManager.setConnectionListener(this);
        // 两个参数是视频地址,如果只显示一路，则将url2设置为null
        String url = RtspConstants.DEFAULT_RTSP_VIDEO_URL1;
        String url2 = RtspConstants.DEFAULT_RTSP_VIDEO_URL2;
        url = "rtsp://admin:xiaomu2012@192.168.144.100:554";
        url2 = "rtsp://admin:xiaomu2012@192.168.144.100:554/Streaming/Channels/201";
        mConnectionManager.setWirelessUrl(url, url2);
        mConnectionManager.checkConnectWithIntent(null);
    }
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        mConnectionManager.checkConnectWithIntent(intent);
    }

    private void initView() {
        mContainer = findViewById(R.id.container);
        mSurfaceView = findViewById(R.id.surface);
        mSurfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                Logcat.d(TAG, "======>onSurfaceCreated...");
                mConnectionManager.notifySurfaceCreate(holder.getSurface());
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                Log.e("SurfaceHolder", "format " + format + " width " + width + " height " + height);
            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                mConnectionManager.notifySurfaceDestroy(holder.getSurface());
            }
        });
    }

    /**
     * 初始化配置
     */
    private void initConfig() {
        //设置解码类型，如果不设置，默认硬解码
        SettingsConfig.setDecodeType(this, IDecodeListener.DECODE_TYPE_HARD);
        //设置Java log是否打印
        SettingsConfig.setLogEnable(false);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mConnectionManager.release();
    }

    @Override
    public void onConnected(int i) {
        //因为回调可能(无线连接方式)在子线程中调用，所以通过Handler切换线程
        mMainHandler.removeMessages(MainHandler.MSG_CONNECTED);
        Message msg = mMainHandler.obtainMessage(MainHandler.MSG_CONNECTED);
        msg.arg1 = i;
        msg.sendToTarget();
    }

    @Override
    public void onDisconnected(int i) {
        mMainHandler.removeMessages(MainHandler.MSG_DISCONNECTED);
        Message msg = mMainHandler.obtainMessage(MainHandler.MSG_DISCONNECTED);
        msg.arg1 = i;
        msg.sendToTarget();
    }

    /**
     * @param connectionType {@link ConnectionListener#TYPE_AOA}
     *                       {@link ConnectionListener#TYPE_WIRELESS}, {@link ConnectionListener#TYPE_USB}
     */
    private void onDeviceConnected(int connectionType) {
        Logcat.e(TAG, "onDeviceConnected, connectionType: " + connectionType);
        if (connectionType == ConnectionListener.TYPE_WIRELESS) {
            //如果是无线连接方式，则支持双路显示，其他连接方式不支持双路显示
            mPreView = new SurfaceView(this);
            mPreView.getHolder().addCallback(new SurfaceHolder.Callback() {
                @Override
                public void surfaceCreated(SurfaceHolder holder) {
                    Logcat.d(TAG, "second onSurfaceCreated...");
                    mConnectionManager.notifySecondSurfaceCreate(holder.getSurface());
                }

                @Override
                public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

                }

                @Override
                public void surfaceDestroyed(SurfaceHolder holder) {
                    Logcat.d(TAG, "second surfaceDestroyed...");
                    mConnectionManager.notifySecondSurfaceDestroy(holder.getSurface());
                }
            });

            mPreView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    System.out.println("mPreView:" + mContainer.getWidth() + " height:" + mContainer.getHeight());

                    String url = "rtsp://admin:xiaomu2012@192.168.144.100:554";
                    String url2 = "rtsp://admin:xiaomu2012@192.168.144.100:554/Streaming/Channels/201";
                    mConnectionManager.setWirelessUrl(url2, url);
                }
            });

            FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(mPreViewWidth, mPreViewHeight);
            layoutParams.gravity = Gravity.BOTTOM | Gravity.START;
            mContainer.addView(mPreView, layoutParams);
        }
    }

    private static class MainHandler extends Handler {
        static final int MSG_CONNECTED = 100;
        static final int MSG_DISCONNECTED = 101;
        final private VideoActivity mMainActivity;

        MainHandler(WeakReference<VideoActivity> reference) {
            mMainActivity = reference.get();
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_CONNECTED:
                    if (mMainActivity != null) {
                        mMainActivity.onDeviceConnected(msg.arg1);
                    }
                    break;
                case MSG_DISCONNECTED:
                    //视情况增加逻辑
                    break;
            }
        }
    }


    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (KeyEvent.KEYCODE_BACK == keyCode) {
            android.app.AlertDialog.Builder normalDialog = new AlertDialog.Builder(VideoActivity.this);
            normalDialog.setTitle("退出视频");
            normalDialog.setMessage("是否退出视频预览?");
            normalDialog.setPositiveButton("确定",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            System.out.println("确定退出视频预览");
                            MainActivity.videoQuit();
                            finish();
                        }
                    });
            normalDialog.setNegativeButton("取消",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            //...To-do
                        }
                    });
            // 显示
            normalDialog.show();
        }

        return false;
    }

    public void setHideVirtualKey(Window window){
        //保持布局状态
        int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE|
                //布局位于状态栏下方
                View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION|
                //全屏
                View.SYSTEM_UI_FLAG_FULLSCREEN|
                //隐藏导航栏
                View.SYSTEM_UI_FLAG_HIDE_NAVIGATION|
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
        if (Build.VERSION.SDK_INT >= 19) {
            uiOptions |= 0x00001000;
        } else {
            uiOptions |= View.SYSTEM_UI_FLAG_LOW_PROFILE;
        }
        window.getDecorView().setSystemUiVisibility(uiOptions);
        window.getDecorView().setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
            @Override
            public void onSystemUiVisibilityChange(int visibility) {
                setHideVirtualKey(window);
            }
        });
    }
}
